package com.example.oa;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String uri = httpServletRequest.getRequestURI();
        if(uri.contains("admin")){
            int role = -1;                           //不输入id和密码非法访问时,防止role=null，网页报错
            if(httpServletRequest.getSession().getAttribute("role")!=null) {
                role = (int) httpServletRequest.getSession().getAttribute("role");
            }
            if(role != 1){
                httpServletRequest.setAttribute("error","Invalid visit");
                httpServletRequest.getRequestDispatcher("/index.jsp").forward(httpServletRequest,httpServletResponse);
            }
        }
        chain.doFilter(request,response);
    }
}
